﻿using Infrastructure;
using Infrastructure.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZR.Infrastructure.ANet
{
    public class ThemeTokenUtil
    {
        /// <summary>
        /// 粤公平主题库请求Token生成
        /// </summary>
        /// <returns></returns>
        public static string CreatToken()
        {
            //获取当前时间秒数并延长5分钟
            DateTimeOffset nowOffset = DateTimeOffset.Now;
            DateTimeOffset epochOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            long timespanStr = (long)((nowOffset - epochOffset).TotalSeconds+300);

            string timeStr=timespanStr.ToString();
            string appkey = AppSettings.GetConfig("ThemeLibraryOptions:AppKey");
            string appsecret = AppSettings.GetConfig("ThemeLibraryOptions:AppSecret");

            string p2 = Base64Util.Base64Encode(timeStr);
            byte[] b = Base64Util.HmacSha1Sign(p2, appsecret);
            string P4 = Base64Util.Base64Encode(b).Replace("+", "-").Replace("/", "_");
            return appkey + "@" + P4 + "@" + p2;
        }

        /// <summary>
        /// 获取请求一张网主题库推送Header
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string,string> GetThemeHeaders()
        {
            Dictionary<string, string> dic = new();
            //获取当前时间秒数
            DateTimeOffset nowOffset = DateTimeOffset.Now;
            DateTimeOffset epochOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            long timespanStr = (long)(nowOffset - epochOffset).TotalSeconds;

            string timeStr = timespanStr.ToString();

            string passid= AppSettings.GetConfig("ThemeLibraryOptions:PassId");
            string passtoken = AppSettings.GetConfig("ThemeLibraryOptions:PassToken");
            string nonce = Guid.NewGuid().ToString();
            string signature = SHA256Util.GetSHA256(timeStr + passtoken + nonce + timeStr);

            dic.Add("x-tif-paasid", passid);
            dic.Add("x-tif-signature", signature);
            dic.Add("x-tif-timestamp", timeStr);
            dic.Add("x-tif-nonce", nonce);

            return dic;



        }



    }
}
